﻿using System;
using System.Globalization;
using System.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using SimplePoll.Web.Models;

namespace SimplePoll.Web.DataAccess
{
    public class PollDataContext : TableServiceContext
    {
        public const string PollTable = "Poll";
        public const string PollAnswerTable = "PollAnswer";
        public const string PollResultTable = "PollResult";

        public PollDataContext(CloudStorageAccount account)
            : this(account.TableEndpoint.ToString(), account.Credentials)
        {
        }

        public PollDataContext(string baseAddress, StorageCredentials credentials) 
            : base(baseAddress, credentials)
        {
            ResolveType = ResolveEntityType;
        }

        public IQueryable<Poll> Polls
        {
            get
            {
                return CreateQuery<Poll>(PollTable);
            }
        }

        public IQueryable<PollAnswer> PollAnswers
        {
            get
            {
                return CreateQuery<PollAnswer>(PollAnswerTable);
            }
        }

        public IQueryable<PollResultRow> PollResults
        {
            get
            {
                return CreateQuery<PollResultRow>(PollResultTable);
            }
        }

        private static Type ResolveEntityType(string name)
        {
            var tableName = name.Split(new[] {'.'}).Last();
            switch(tableName)
            {
                case PollTable:
                    return typeof (Poll);
                case PollAnswerTable:
                    return typeof (PollAnswer);
                case PollResultTable:
                    return typeof (PollResultRow);
            }

            throw new ArgumentException(
                string.Format(CultureInfo.CurrentCulture,
                "Could not resolve the table name '{0}' to a known entity type.", 
                name));
        }
    }
}